package com.fj.netty.chat.server;

import com.fj.netty.chat.handler.*;
import com.fj.netty.chat.protocol.MessageCodec;
import com.fj.netty.chat.protocol.MessageLengthFieldDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端
 * @author fj
 * @date 2024/1/11 14:09
 */
@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //空闲连接检测器，超过指定时间会触发对应事件
                            ch.pipeline().addLast(new IdleStateHandler(5,0,0));
                            //自定义事件监听器，处理特定事件
                            ch.pipeline().addLast(new ChannelDuplexHandler(){
                                @Override
                                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                    if (evt instanceof IdleStateEvent){
                                        IdleStateEvent event = (IdleStateEvent) evt;
                                        if (event.state()== IdleState.READER_IDLE) {
                                            log.debug("5秒内无请求，关闭连接");
                                            ctx.channel().close();
                                        }
                                    }
                                }
                            });
                            ch.pipeline().addLast(new MessageLengthFieldDecoder());
//                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new MessageCodec());
                            ch.pipeline().addLast(new LoginRequestMessageHandler());
                            ch.pipeline().addLast(new ChatRequestMessageHandler());
                            ch.pipeline().addLast(new GroupChatRequestMessageHandler());
                            ch.pipeline().addLast(new GroupCreateRequestMessageHandler());
                            ch.pipeline().addLast(new GroupJoinResponseMessageHandler());
                            ch.pipeline().addLast(new GroupMembersRequestMessageHandler());
                            ch.pipeline().addLast(new GroupQuitRequestMessageHandler());
                            ch.pipeline().addLast(new QuitHandler());
                        }
                    });
            Channel channel = serverBootstrap.bind("127.0.0.1", 6789).sync().channel();
            channel.closeFuture().sync();
        }catch (Exception e){
            log.error("服务端启动异常",e);
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
